import type { FormInstance, FormRules } from 'element-plus'
import qs from 'query-string'
import { computed, onMounted, reactive, toRefs } from 'vue'
import { useRoute, useRouter } from 'vue-router'

import { authApi } from '@/apis'
import { useSettingStore, useUserStore } from '@/store'

export function useLogin() {
  const state = reactive({
    loading: false,
    redirect: null as Nullable<string>,
    otherQuery: {},
    formRef: {} as FormInstance,
    formModel: {
      userName: '',
      password: '',
      captchaValue: ''
    },
    formRules: {
      userName: [{ required: true, message: '请输入账号', trigger: 'blur' }],
      password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
      captchaValue: [
        { required: true, message: '请输入验证码', trigger: 'blur' }
      ]
    } as FormRules,
    captcha: {
      id: '',
      imageBase64: ''
    }
  })

  const route = useRoute()
  const router = useRouter()
  const settingStore = useSettingStore()
  const userStore = useUserStore()

  const title = computed(() => settingStore.title)

  function initQuery() {
    const { query } = route

    if (query) {
      const str = query.redirect as string

      if (str) {
        const { url, query } = qs.parseUrl(str)

        state.redirect = url
        state.otherQuery = query
      }
    }
  }

  async function handleGetCaptcha() {
    state.captcha = await authApi.getCaptcha()
  }

  function handleSubmit() {
    state.formRef.validate(async valid => {
      if (valid) {
        state.loading = true
        userStore
          .login({
            ...state.formModel,
            captchaId: state.captcha.id
          })
          .then(() => {
            router.replace({
              path: state.redirect || '/',
              query: state.otherQuery
            })
          })
          .finally(() => {
            state.loading = false
          })
      }
    })
  }

  onMounted(() => {
    initQuery()
    handleGetCaptcha()
  })

  return {
    ...toRefs(state),
    title,
    handleGetCaptcha,
    handleSubmit
  }
}
